<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
// 导入 echarts 和 theme
import * as echarts from 'echarts'
//  图表的 resize 相关事件
import resize from './mixin/resize'
// require('./theme')
require('./dark')
require('./walden')
export default {
  mixins: [resize],
  props: {
    // 样式以及类名
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    loading: {
      type: Boolean,
      default: false
    },
    theme: {
      type: String,
      default: 'dark'
    },
    options: {
      type: Object,
      default: () => {},
      required: true
    }
  },
  data () {
    return {
      chart: null,
      chartLoading: false
    }
  },
  watch: {
    options: {
      deep: true,
      handler (val) {
        this.setOptions(val)
      }
    },
    loading (n, o) {
      if (!n && o) {
        this.hideLoading()
      } else if (n) {
        this.showLoading()
      }
    }
  },
  // mounted 钩子中创建图表
  mounted () {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  // 实例即将销毁时清空/注销实例
  beforeDestroy () {
    if (!this.chart) {
      return
    }
    // dispose 销毁方法 echarts
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    // 初始化实例，并且渲染
    initChart () {
      this.chart = echarts.init(this.$el, this.theme)
      if (this.loading) {
        this.showLoading()
      }
      this.setOptions(this.options)
    },
    showLoading () {
      this.chart.showLoading('default', {
        text: '加载中，请请稍后...',
        color: '#1890ff'
      })
    },
    hideLoading () {
      this.chart.hideLoading()
    },
    setOptions (option) {
      this.chart.setOption(option)
    }
  }
}
</script>
